package soulkun.library.utils.uri

import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.annotation.IdRes
import androidx.core.content.FileProvider
import soulkun.library.utils.string.StringUtils.isEmpty
import java.io.File


object UriUtils {

    fun getDrawableUriString(context: Context, @IdRes resId: Int): String {
        return "${ContentResolver.SCHEME_ANDROID_RESOURCE}:" +
                "//${context.resources.getResourcePackageName(resId)}" +
                "/${context.resources.getResourceTypeName(resId)}" +
                "/${context.resources.getResourceEntryName(resId)}"
    }

    fun getDrawableUri(context: Context, @IdRes resId: Int): Uri {
        return Uri.parse(getDrawableUriString(context, resId))
    }

    fun getFileUri(context: Context, file: File, fileType: String): Uri? {
        var uri: Uri? = null
        // 低版本直接用 Uri.fromFile
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(file)
        } else {
//            //  使用 FileProvider 会在某些 app 下不支持（在使用FileProvider 方式情况下QQ不能支持图片、视频分享，微信不支持视频分享）
//            uri = FileProvider.getUriForFile(context,
//                    "gdut.bsx.videoreverser.fileprovider",
//                    file)
//            val cR = context.contentResolver
//            if (uri != null && !isEmpty(uri.toString())) {
//            val fileType = cR.getType(uri)
            // 使用 MediaStore 的 content:// 而不是自己 FileProvider 提供的uri，不然有些app无法适配
//            if (fileType != null) {
            if (fileType.contains("video/")) {
                uri = getVideoContentUri(context, file)
            } else if (fileType.contains("image/")) {
                uri = getImageContentUri(context, file)
            } else if (fileType.contains("audio/")) {
                uri = getAudioContentUri(context, file)
            }
//            }
//            }
        }
        return uri
    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param imageFile
     * @return content Uri
     */
    fun getImageContentUri(context: Context, imageFile: File): Uri? {
        val filePath = imageFile.absolutePath
        val cursor: Cursor? = context.contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Images.Media._ID), MediaStore.Images.Media.DATA.toString() + "=? ", arrayOf(filePath), null)
        return if (cursor != null && cursor.moveToFirst()) {
            val id: Int = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
            val baseUri = Uri.parse("content://media/external/images/media")
            Uri.withAppendedPath(baseUri, "" + id)
        } else {
            if (imageFile.exists()) {
                val values = ContentValues()
                values.put(MediaStore.Images.Media.DATA, filePath)
                context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
            } else {
                null
            }
        }
    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param videoFile
     * @return content Uri
     */
    fun getVideoContentUri(context: Context, videoFile: File): Uri? {
        val filePath = videoFile.absolutePath
        val cursor: Cursor? = context.contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Video.Media._ID), MediaStore.Video.Media.DATA.toString() + "=? ", arrayOf(filePath), null)
        return if (cursor != null && cursor.moveToFirst()) {
            val id: Int = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
            val baseUri = Uri.parse("content://media/external/video/media")
            Uri.withAppendedPath(baseUri, "" + id)
        } else {
            if (videoFile.exists()) {
                val values = ContentValues()
                values.put(MediaStore.Video.Media.DATA, filePath)
                context.contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values)
            } else {
                null
            }
        }
    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param audioFile
     * @return content Uri
     */
    fun getAudioContentUri(context: Context, audioFile: File): Uri? {
        val filePath = audioFile.absolutePath
        val cursor: Cursor? = context.contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Audio.Media._ID), MediaStore.Audio.Media.DATA.toString() + "=? ", arrayOf(filePath), null)
        return if (cursor != null && cursor.moveToFirst()) {
            val id: Int = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
            val baseUri = Uri.parse("content://media/external/audio/media")
            Uri.withAppendedPath(baseUri, "" + id)
        } else {
            if (audioFile.exists()) {
                val values = ContentValues()
                values.put(MediaStore.Audio.Media.DATA, filePath)
                context.contentResolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values)
            } else {
                null
            }
        }
    }

}